package xworker.gluon.glisten.application;

import com.gluonhq.charm.glisten.application.AppManager;
import com.gluonhq.charm.glisten.visual.Swatch;
import org.xmeta.ActionContext;
import org.xmeta.Thing;
import xworker.javafx.beans.property.PropertyFactory;
import xworker.javafx.util.JavaFXUtils;
import xworker.lang.executor.Executor;

public class ThingApplication {
    static{
        PropertyFactory.regist(AppManager.class, "titleProperty", o -> {
            AppManager obj = (AppManager) o;
            return obj.titleProperty();
        });
        PropertyFactory.regist(AppManager.class, "swatchProperty", o -> {
            AppManager obj = (AppManager) o;
            return obj.swatchProperty();
        });
    }

    private static final String TAG = ThingApplication.class.getName();

    Thing thing;
    ActionContext actionContext;

    public ThingApplication(Thing thing, ActionContext actionContext){
        this.thing = thing;
        this.actionContext = actionContext;
    }

    public String getTitle(){
        return JavaFXUtils.getString(thing, "title", actionContext);
    }

    public void init(){
        try {
            AppManager appManager = AppManager.getInstance();

            String swatch = thing.getStringBlankAsNull("swatch");
            if (swatch != null) {
                appManager.setSwatch(Swatch.valueOf(swatch));
            }

            for (Thing child : thing.getChilds()) {
                Executor.info(TAG, "Do create method of app manager child, path=" + child.getMetadata().getPath());
                child.doAction("create", actionContext);
            }
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void create(ActionContext actionContext){

    }

    public static void createViews(ActionContext actionContext){
        Thing self = actionContext.getObject("self");
        Executor.info(TAG, "Create views, path=" + self.getMetadata().getPath());
        AppManager appManager = AppManager.getInstance();
        for(Thing child : self.getChilds()){
            String name = child.getMetadata().getName();
            appManager.removeViewFactory(name);
            appManager.addViewFactory(name, new ThingViewFactory(child, actionContext));
            Executor.info(TAG, "Add view factory, name=" + name +", path=" + child.getMetadata().getPath());
        }
    }
}
